import Vue from 'vue'
import clonedeep from 'lodash.clonedeep'
export function getCurrentOrganizationId () {
  let userInfo = sessionStorage.getItem('userInfo')
  userInfo = userInfo ? JSON.parse(userInfo) : {}
  return userInfo.tenantId
}
export function getCurrentUserId() {
  let userInfo = sessionStorage.getItem('userInfo')
  userInfo = userInfo ? JSON.parse(userInfo) : {}
  return userInfo.loginName
}
/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent () {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}
export function handleScrollHeader (callback) {
  let timer = 0
  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = ''
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}
export function isIE () {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}
export function browser () {
  const userAgent = window.navigator.userAgent // 取得浏览器的userAgent字符串
  const isOpera = userAgent.indexOf('Opera') > -1 // 判断是否Opera浏览器
  const isIEs = (() => 'ActiveXObject' in window)() // 判断是否IE浏览器
  const isEdge = userAgent.indexOf('Edge') > -1 // 判断是否IE的Edge浏览器
  const isFF = userAgent.indexOf('Firefox') > -1 // 判断是否Firefox浏览器
  const isSafari = userAgent.indexOf('Safari') > -1 && userAgent.indexOf('Chrome') == -1 // 判断是否Safari浏览器
  var isChrome = userAgent.indexOf('Chrome') > -1 && userAgent.indexOf('Safari') > -1 // 判断Chrome浏览器
  if (isIEs) {
    return 'IE'
  }
  if (isEdge) {
    return 'Edge'
  }
  if (isFF) {
    return 'Fox'
  }
  if (isSafari) {
    return 'Safari'
  }
  if (isChrome) {
    return 'Chrome'
  }
  if (isOpera) {
    return 'Opera'
  }
}
/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate (id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}
/**  判断传过来的值除以3的余数，若大于0则添加  格式化
 *@param list  []
 * ***/
export function forMartList (list) {
  let inMoreNum = ''
  if (list) {
    list.forEach((v) => {
      inMoreNum = v.list.length % 3
      if (inMoreNum > 0) {
        for (let i = 0; i < 3 - inMoreNum; i++) {
          v.list.push({
            'listName': '',
            'listType': 0
          })
        }
      }
    })
    return list
  } else {
    return ''
  }
}
/**
* @param {Function} func
* @param {number} wait
* @param {boolean} immediate
* @return {*}
  */
export function debounce (func, wait, immediate) {
  let timeout, args, context, timestamp, result
  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp
    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }
  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }
    return result
  }
}
/**
 * 深拷贝
 * @param {Object} source
 * @returns {Object}
 */
// export function deepClone (source) {
//   if (!source && typeof source !== 'object') {
//     throw new Error('error arguments', 'deepClone')
//   }
//   const targetObj = source.constructor === Array ? [] : {}
//   Object.keys(source).forEach(keys => {
//     if (source[keys] && typeof source[keys] === 'object') {
//       targetObj[keys] = deepClone(source[keys])
//     } else {
//       targetObj[keys] = source[keys]
//     }
//   })
//   return targetObj
// }
/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime (time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}
/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime (time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()
  const diff = (now - d) / 1000
  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}
/**
 * 产生随机整数，包含下限值，包括上限值
 * @param {Number} lower 下限
 * @param {Number} upper 上限
 * @return {Number} 返回在下限到上限之间的一个随机整数
 */
export function random (lower, upper) {
  return Math.floor(Math.random() * (upper - lower + 1)) + lower
}
export function listToTree (list) {
  let temp = clonedeep(list)
  // 将数据存储为 以 id 为 key 的 map 索引数据
  let map = {}
  temp.forEach((item) => {
    map[item.id] = item
  })
  // 把平级变成树
  let resData = []
  temp.forEach(item => {
    let parent = map[item.parentId]
    if (parent) {
      (parent.children || (parent.children = [])).push(item)
    } else {
      resData.push(item)
    }
  })
  // 将树进行排序
  resData.sort((a,b) => a.rank - b.rank)
  function loop (obj) {
    if (obj.children) {
      obj.children.sort((a,b) => a.rank -b.rank)
      obj.children.forEach(item => {
        loop(item)
      })
    }
  }
  resData.forEach(item => {
    loop(item)
  })
  return resData
}
export const timeFormat = (time, format = 'YYYY-MM-DD HH:mm:ss') => time ? moment(time).format(format) : time
export function mockData(params) {
  const Mock = require('mockjs')
  const Random = Mock.Random
  // const newsData = function () {
    let articles = []
    for (let i = 0; i < 8; i++) {
      let newsObj = {
        'ImportantGrade|1': ['L', 'A', 'B', 'C', '一般重品', '客户重品'],
        InternalOrderNumber: Random.csentence(1, 3),
        'Market|1': ['国内', '国际', '国内及国际'],
        'PartsCategory|1': ["传动类", "机械结构类", "液压类", "电气类"],
        PlanningYear: "2021",
        'ProjectBudget|1-100': 100,
        ProjectMananger: Random.csentence(1, 3),
        'ProjectSmallType|1': ["工艺技术研究", "客户订单", "数字化手段提升", "技术开发", "试验能力提升", "新领域", "型谱扩展（型号不同）", "升级换代、降成本或提升质量", "工艺规划或技改"],
        ProjectType: "关键零部件开发项目",
        ResponsibleProject: false,
        'ProductCategory|1': ["岸边集装箱起重机", "地热钻机", "矿用自卸车", "旋挖钻机", "大港机吊具", "湿喷机", "智能控制系统", "铣刨机", "纯电动港口牵引车"],
        'allowCompleteFlag|1-2': true,
        calendarReference: Random.date(),
        creator: Random.first(),
        description: Random.csentence(3, 5),
        'isPlanningProject|1': ['是', '否'],
        lastChecksum: Random.datetime(),
        modeofdevelopment: Random.csentence(1, 5),
        modifier: Random.last(),
        nsegmenttype: Random.csentence(2, 4),
        obsReference: Random.csentence(2, 4),
        oid: Random.id(),
        planEndDate: Random.datetime(),
        planStartDate: Random.datetime(),
        projectAbbreviation: Random.csentence(2, 7) + Random.zip(),
        projectGroupReference: Random.csentence(3, 5) + Random.zip(),
        projectName: Random.csentence(2, 7),
        projectShortName: "P"+Random.zip(),
        'riskLevel|1': ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
        startDate: Random.date(),
        'state.state|1': ["申请中", "已立项", "立项中", "驳回立项", "待处理", "暂停", "申请完成", "立项准备", "执行中", "已结束", "废弃", "已验收"],
        'thePersistInfo.createStamp': Random.date(),
        'thePersistInfo.modifyStamp': Random.date(),
      }
      let obj = Mock.mock(newsObj)
      articles.push(obj)
    }
    // return {
    //   articles: articles
    // }
  // }
  // console.log(Mock.mock(newsData));
  return articles
}
// 导出
export function saveFile(data, name) {
  try {
    const blobUrl = window.URL.createObjectURL(data)
    const a = document.createElement('a')
    a.style.display = 'none'
    a.download = name
    a.href = blobUrl
    a.click()
  } catch (error) {
    Vue.prototype.$message.error('导出文件出错')
  }
}
// 数组对象去重
export function handleArr(arr) {
  let result = []
  let obj = {}
  for (var i = 0; i < arr.length; i++) {
    if (!obj[arr[i].idKey]) {
       result.push(arr[i]);
       obj[arr[i].idKey] = true;
    }
  }
  return result
}
// 项目任务书表格参数标准化
export function standardParams(columns, tableData, filterKey = ['oid']) {
  if (!tableData.length) return []
  let columnsArr = columns.map(item => item.key)
  let standardTableData = []
  tableData.forEach(item => {
    let newItem = {}
    for (let key in item) {
      if (filterKey.includes(key) || columnsArr.includes(key)) {
        if (!item[key] && item[key] !== 0) {
          newItem[key] = ''
        } else {
          newItem[key] = item[key]
        }
      }
    }
    standardTableData.push(newItem)
  })
  return standardTableData
}